package com.dman.multi.algo;

import java.util.List;

import com.dman.multi.core.NetworkStream;
import com.dman.multi.core.Section;


public class MaxSectionAlgo implements SectionAlgo {

	@Override
	public int createSection(List<Section> secList) throws SectionCreationException{
		
		// declare the variables for this function
		long max = 0;
		long diff = 0;
		int index = 0;
		Section prevSec = null;
		Section sec = secList.get(0);
		long size = sec.getSize();
		
		// find out the interval within which max bytes need to be downloaded
		for(int i = 1; i <= secList.size(); ++i){
			prevSec = secList.get(i - 1);
			if(i < secList.size())
				sec = secList.get(i);
			diff = sec.getStartPos() - prevSec.getCurrPos();
			if(sec == prevSec)
				diff = size - sec.getCurrPos();
			
			if(max < diff){
				max = diff;
				index = i - 1;
			}
		}
		
		// if difference is less than buffer size
		if(max < NetworkStream.BUFFER_SIZE)
			throw new SectionCreationException("Section size less than buffer size");
		
		// insert the new section into the position pointed by index
		sec = secList.get(index);
		long newSecStart = sec.getCurrPos() + max / 2;
		try {
			Section newSec = new Section(sec.getStrUrl(), newSecStart);
			synchronized (secList) {
				secList.add(index + 1, newSec);
			}
		} catch (Exception e){
			//	System.out.println("Maximum number of connections to this host reached: " + secList.size());
			throw new SectionCreationException("Maximum number of connections to this host reached: " + secList.size());
		}
		
		return index + 1;
	}

}
